<?php
class controller_exchange extends model_exchange
{
    public function products_subcategory_search_select(){
        $id = $this->existsKeyInArray('id',$_GET,'N');
        echo json_encode($this->mod_sub_category($id,'id,title'));
    }

    # region 商品分类管理
    private function category_get_args($get){
        $para = $get ? $_GET : $_POST;
        $args = array();
        $args['sKey'] = $this->existsKeyInArray('sKey',$para,'S');
        $args['categoryid'] = $this->existsKeyInArray('categoryid',$para,'N');
        $args['ps'] = $this->existsKeyInArray('ps',$para,'N',$this->pagesize);
        return $args;
    }
    private function category_page_args($args){
        $page = array();
        if(!empty($args['sKey'])) $page['sKey'] = $args['sKey'];
        if(!empty($args['categoryid'])) $page['categoryid'] = $args['categoryid'];
        if(!empty($args['ps'])) $page['ps'] = $args['ps'];
        $page['page'] = '{page}';
        return $page;
    }
    public function category(){
        $parent_category = $this->mod_parentcategory();
        $args = $this->category_get_args(true);
        $page_args = $this->category_page_args($args);
        $args['page_current'] = $this->get_page();
        $datas = $this->mod_category_list($args);
        $this->display('exchange/category',array(
            'parent_category' => $parent_category,
            'datas' => $datas,
            'basepath' => 'exchange/category',
            'page_url' => http_build_query($page_args),
            'searchdata' => $args,
        ));
    }
    /*
    * view 商品分类搜索
    */
    public function category_search(){
        $para = $_GET;

    }
    /*
    * view 添加商品分类
    */
    public function category_add(){
        $parentcategory = $this->mod_parentcategory();
        $this->display('exchange/category_add',array(
            'basepath' => '/exchange/category',
            'parentcategory' => $parentcategory,
            'maxsort' => $this->table_maxsort('@@product_category','sort','1'),
        ));
    }
    /*
    * view 编辑商品分类
    */
    public function category_edit(){
        $id = intval($_GET['id']);
        $parentcategory = $this->mod_parentcategory();
        $data = $this->mod_category_item($id);
        $this->display('exchange/category_edit',array(
            'basepath' => '/exchange/category',
            'data' => $data,
            'parentcategory' => $parentcategory,
        ));
    }
    /*
    * 商品分类参数处理
    */
    private function category_add_edit_args(){
        $para = $_POST;
        $args['id'] = $this->existsKeyInArray('id',$para,'N');
        $args['title'] = $this->existsKeyInArray('title',$para,'S');
        $args['subtitle'] = $this->existsKeyInArray('subtitle',$para,'S');
        $args['parentid'] = $this->existsKeyInArray('parentid',$para,'S');
        $args['icon'] = $this->existsKeyInArray('icon',$para,'S','#');
        $args['bgcolor'] = $this->existsKeyInArray('bgcolor',$para,'S');
        $args['txtcolor'] = $this->existsKeyInArray('txtcolor',$para,'S');
        $args['parents'] = $this->existsKeyInArray('parentis',$para,'N');
        $args['sort'] = $this->existsKeyInArray('sort',$para,'N');
        if(empty($args['title'])) core::error("分类名称不能为空");
        return $args;
    }
    /*
    * 添加商品分类-保存
    */
    public function category_add_save(){
        if(!$this->post) core::__403();
        $para = $this->category_add_edit_args();
        unset($para['id']);
        $insertid = $this->mod_category_save($para);
        if(!$insertid) core::error("添加[".$para['title']."]失败");
        $this->addLog($this->authid,__FUNCTION__,$insertid);
        $this->dialogue(array(
            'type' => 'success',
            'text' => "添加[".$para['title']."]成功",
            'auto' => true,
            'yes'  => array(
                'text' => '继续',
            ),
            'yes'  => array(
                'text' => '返回',
                'func' => 'JumpMainFrame("/exchange/category");',
            ),
        ));
    }
    /*
    * 编辑商品分类 - 保存
    */
    public function category_edit_save(){
        if(!$this->post) core::__403();
        $para = $this->category_add_edit_args(true);
        $update_args = array('id'=>intval($para['id']));
        unset($para['id']);
        $updateid = $this->mod_category_save($para,$update_args,true);
        if(!$updateid) core::error("更新[".$para['title']."]失败");
        $this->addLog($this->authid,__FUNCTION__,$update_args['id']);
        $this->dialogue(array(
            'type' => 'success',
            'text' => "更新[".$para['title']."]成功",
            'auto' => true,
            'yes'  => array(
                'text' => '返回',
                'func' => 'JumpMainFrame("/exchange/category");',
            ),
        ));
    }
    /*
    * 商品分类状态变更 通过 GET 方式传送参数
    * @param $id int 商品分类的ID
    */
    public function category_state(){
        $id = intval($_GET['id']);
        $updateid = $this->update_state('@@product_category',$id);
        if(!$updateid) core::error("状态更新失败");
        $this->addLog($this->authid,__FUNCTION__,$id,'');
        $this->dialogue(array(
            'type' => 'success',
            'text' => "状态更新成功",
            'auto' => true,
            'yes'  => array(
                'text' => '返回',
                'func' => 'JumpMainFrame("/exchange/category");',
            ),
        ));
    }
    # endregion

    # region 商品管理
    private  function  products_get_args($get=true){
        $para = $get ? $_GET : $_POST;
        $args = array();
        $args['sKey'] = $this->existsKeyInArray('sKey',$para,'S');
        $args['categoryid'] = $this->existsKeyInArray('categoryid',$para,'N');
        $args['categorysubid'] = $this->existsKeyInArray('categorysubid',$para,'N');
        $args['ps'] = $this->existsKeyInArray('ps',$para,'N',$this->pagesize);
        return $args;
    }
    //商品列表搜索-分页参数
    private function products_page_args($args){
        $page_args = array();
        if(!empty($args['sKey'])) $page_args['sKey'] = $args['sKey'];
        if(!empty($args['categoryid'])) $page_args['categoryid'] = $args['categoryid'];
        if(!empty($args['categorysubid'])) $page_args['categorysubid'] = $args['categorysubid'];
        if(!empty($args['ps'])) $page_args['ps'] = $args['ps'];
        $page_args['page'] = '{page}';
        return $page_args;
    }
    //商品列表
    public function products(){
        $args = $this->products_get_args(true);
        $page_args = $this->products_page_args($args);
        $args['page_current'] = $this->get_page();

        $datas = $this->mod_product_products($args);
        $args['page_max'] = $this->get_maxpage($args['ps'],$datas['record']);

        $basepath = '/exchange/products';
        $parentcategory = $this->mod_parentcategory();
        $subcategory = array();
        if(!empty($args['categoryid']) && !empty($args['categorysubid'])){
            $subcategory = $this->mod_sub_category($args['categoryid'],'id,title');
        }
        $this->display("exchange/products",array(
            'basepath' => $basepath,
            'parent_category' => $parentcategory,
            'sub_category' => $subcategory,
            'datas' => $datas['datas'],
            'record' => $datas['record'],
            'page_max' => $args['page_max'],
            'page_current' => $args['page_current'],
            'page_url' => http_build_query($page_args),
            'extra' => '',
            'searchdata' => $args,
            'container' => '#iframe'
        ));
    }
    //添加商品VIEW
    public  function products_add(){
        $_cid = $this->existsKeyInArray('categoryid',$_REQUEST,'N');
        $_scid = $this->existsKeyInArray('categorysubid',$_REQUEST,'N');
        if(!$_cid) core::error('未指定商品分类，请从商品分类列表中开始添加商品');
        $this->display("exchange/products_add",array(
            'basepath' => '/exchange/products',
            'default_cid' => $_cid,
            'default_scid' => $_scid,
            'number' => $this->randNumber(1),
            'uservip' => $this->mod_user_vip(),
            'agent' => $this->mod_agent_level(),
            'parent_category' => $this->mod_parentcategory(),
            'sub_category' => $this->mod_sub_category($_cid,'id,title'),
            'maxsort' => $this->table_maxsort('@@products','sort','1'),
        ));
    }
    //编辑商品VIEW
    public function products_edit(){
        $code = $this->existsKeyInArray('code',$_REQUEST,'S');
        $_cid = $this->existsKeyInArray('categoryid',$_REQUEST,'N');
        $_scid = $this->existsKeyInArray('categorysubid',$_REQUEST,'N');
        if(!$code) core::__403();
        if(!$_cid) core::error('商品分类参数错误，请返回重试');
        $this->display("exchange/products_edit",array(
            'basepath' => '/exchange/products',
            'data' => $this->mod_product_item($code),
            'default_cid' => $_cid,
            'default_scid' => $_scid,
            'uservip' => $this->mod_user_vip(),
            'agent' => $this->mod_agent_level(),
            'parent_category' => $this->mod_parentcategory(),
            'sub_category' => $this->mod_sub_category($_cid,'id,title'),
        ));
    }
    //删除指定商品
    public function products_delete(){
        $id = $this->existsKeyInArray('id',$_GET,'N');
        $code = $this->existsKeyInArray('code',$_GET,'S');
        if(!$id) core::__403();
        $delid = $this->mod_products_delete($id,$code);
        if(!$delid) core::error('删除失败');
        $this->addLog($this->authid,__FUNCTION__,$id);
        $this->dialogue(array(
            'type' => 'success',
            'text' => "操作成功",
            'auto' => true,
            'yes'  => array(
                'text' => '我知道了',
                'func' => '$("#btn_refresh").trigger();',
            ),
        ));

    }
    //更新状态
    public function products_state(){
        $id = $this->existsKeyInArray('id',$_GET,'N');
        $field = $this->existsKeyInArray('field',$_GET,'S');
        $page_args = array(
            'page' => $this->existsKeyInArray('page',$_GET,'N',1),
            'categoryid' => $this->existsKeyInArray('categoryid',$_GET,'N'),
            'categorysubid' => $this->existsKeyInArray('categorysubid',$_GET,'N'),
        );
        if(!$id || empty($field)) core::__403();
        $updateid = $this->update_state('@@products',$id,$field);
        if(!$updateid) core::error('状态更新失败');
        $this->addLog($this->authid,__FUNCTION__,$id,'');
        $this->dialogue(array(
            'type' => 'success',
            'text' => "状态更新成功",
            'auto' => true,
            'yes'  => array(
                'text' => '我知道了',
                'func' => 'JumpMainFrame("/exchange/products?'.http_build_query($page_args).'");',
            ),
        ));
    }
    //添加或编辑商品时处理参数
    private function products_add_edit_args(){
        $args = array(
            'id' => $this->existsKeyInArray('id',$_POST,'N'),
            'title' => $this->existsKeyInArray('title',$_POST,'S'),
            'code' => $this->existsKeyInArray('code',$_POST,'S'),
            'keys' => $this->existsKeyInArray('keys',$_POST,'S'),
            'icon1' => $this->existsKeyInArray('icon1',$_POST,'S'),
            'icon2' => $this->existsKeyInArray('icon2',$_POST,'S'),
            'icon3' => $this->existsKeyInArray('icon3',$_POST,'S'),
            'icon4' => $this->existsKeyInArray('icon4',$_POST,'S'),
            'icon5' => $this->existsKeyInArray('icon5',$_POST,'S'),
            'pricenet' => $this->existsKeyInArray('pricenet',$_POST,'F'),
            'price' => $this->existsKeyInArray('price',$_POST,'F'),
            'sales' => $this->existsKeyInArray('sales',$_POST,'N'),
            'inventory' => $this->existsKeyInArray('inventory',$_POST,'N'),
            'pricesales' => $this->existsKeyInArray('pricesales',$_POST,'F'),
            'pricescore' => $this->existsKeyInArray('pricescore',$_POST,'F'),
            'salesfromtime' => $this->existsKeyInArray('salesfromtime',$_POST,'N'),
            'salestotime' => $this->existsKeyInArray('salestotime',$_POST,'N'),
            'state' => $this->existsKeyInArray('state',$_POST,'N'),
            'commentstate' => $this->existsKeyInArray('commentstate',$_POST,'N'),
            'sort' => $this->existsKeyInArray('sort',$_POST,'N'),
            'unit' => $this->existsKeyInArray('unit',$_POST,'S'),
            'heft' => $this->existsKeyInArray('heft',$_POST,'F'),
            'reminder' => $this->existsKeyInArray('reminder',$_POST,'S'),
            'categoryid' => $this->existsKeyInArray('categoryid',$_POST,'N'),
            'categorysubid' => $this->existsKeyInArray('categorysubid',$_POST,'N'),
            'recommend' => $this->existsKeyInArray('recommend',$_POST,'N'),
            'buyforvip' => $this->existsKeyInArray('buyforvip',$_POST,'N'),
            'buyforagent' => $this->existsKeyInArray('buyforagent',$_POST,'N'),
            'minnum' => $this->existsKeyInArray('minnum',$_POST,'N',1),
            'maxnum' => $this->existsKeyInArray('maxnum',$_POST,'N',0),
            'website' => $this->existsKeyInArray('website',$_POST,'S'),
            'score' => $this->existsKeyInArray('score',$_POST,'N'),
        );
        if(empty($args['title'])) core::error('商品标题不能为空');
        if(empty($args['keys'])) core::error('商品搜索关键字不能为空');
        if(empty($args['unit'])) core::error('商品的单位不能为空');
        if(empty($args['pricenet'])) core::error('商品的网上售价不能为空');
        if(empty($args['price'])) core::error('商品的当前售价不能为空');
        if(empty($args['minnum'])) core::error('须指定最低购买数量');
        //如果没有图示的将默认不展示
        if(empty($args['icon']) || $args['icon']=='#') $args['state'] = 0;
        $args_con = array(
            'content' => $this->existsKeyInArray('content',$_POST,'S'),
            'code' => $args['code'],
        );
        return array(
            'args' => $args,
            'cont' => $args_con,
        );
    }
    //添加商品保存事件
    public function products_add_save(){
        if(!$this->post) core::__403();
        $args = $this->products_add_edit_args();
        //添加商品信息到主表
        unset($args['args']['id']);
        $insertid = $this->table_row_save('@@products',$args['args']);
        if(!$insertid) core::error("添加[ {$args['args']['title']} ]失败");

        //添加商品详情到详情表
        $this->table_row_save_replace('@@products_con', $args['cont']);
        $this->addLog($this->authid,__FUNCTION__,$insertid);
        $this->dialogue(array(
            'type' => 'success',
            'text' => "添加[ {$args['args']['title']} ]成功",
            'auto' => true,
            'yes'  => array(
                'text' => '继续添加',
                'func' => 'JumpMainFrame("/exchange/products_add?categoryid='.$args['args']['categoryid'].'&categorysubid='.$args['args']['categorysubid'].'");',
            ),
            'no'  => array(
                'text' => '查看商品',
                'func' => 'JumpMainFrame("/exchange/products?categoryid='.$args['args']['categoryid'].'&categorysubid='.$args['args']['categorysubid'].'");',
            ),
        ));
    }
    public function products_edit_save(){
        if(!$this->post) core::__403();
        $args = $this->products_add_edit_args();
        //var_dump($args['args']);
        //exit;
        $id = intval($args['args']['id']);
        $code = $args['args']['code'];
        unset($args['args']['id']);
        unset($args['args']['code']);
        //添加商品信息到主表
        $updateid = $this->table_row_save('@@products',$args['args'],array('id'=>$id),true);
        //添加商品详情到详情表
        $this->table_row_save_replace('@@products_con', $args['cont']);
        $this->addLog($this->authid,__FUNCTION__,$id);
        $this->dialogue(array(
            'type' => 'success',
            'text' => "更新[ {$args['args']['title']} ]成功",
            'auto' => true,
            'yes'  => array(
                'text' => '我知道了',
                'func' => 'JumpMainFrame("/exchange/products?categoryid='.$args['args']['categoryid'].'&categorysubid='.$args['args']['categorysubid'].'");',
            ),
        ));
    }
    # endregion

    # region 兑换订单管理
    private  function  orders_get_args($get=true){
        $para = $get ? $_GET : $_POST;
        $args = array();
        $fromTime = date('Y-m-d',time()-86400*365);
        $args['sKey'] = $this->existsKeyInArray('sKey',$para,'S');
        $args['fromTime'] = $this->existsKeyInArray('fromTime',$para,'S',$fromTime);
        $args['toTime'] = $this->existsKeyInArray('toTime',$para,'S',$fromTime);
        $args['ps'] = $this->existsKeyInArray('ps',$para,'N',$this->pagesize);
        return $args;
    }
    //商品列表搜索-分页参数
    private function orders_page_args($args){
        $page_args = array();
        if(!empty($args['sKey'])) $page_args['sKey'] = $args['sKey'];
        if(!empty($args['fromTime'])) $page_args['fromTime'] = $args['fromTime'];
        if(!empty($args['toTime'])) $page_args['toTime'] = $args['toTime'];
        if(!empty($args['ps'])) $page_args['ps'] = $args['ps'];
        $page_args['page'] = '{page}';
        return $page_args;
    }
    public function orders()
    {
        $args = $this->orders_get_args(true);
        $page_args = $this->orders_page_args($args);
        $args['page_current'] = $this->get_page();

        $datas = $this->mod_orders_list($args);
        $args['page_max'] = $this->get_maxpage($args['ps'],$datas['record']);

        $basepath = '/exchange/orders';

        $this->display("exchange/orders",array(
            'basepath' => $basepath,
            'datas' => $datas['datas'],
            'record' => $datas['record'],
            'page_max' => $args['page_max'],
            'page_current' => $args['page_current'],
            'page_url' => http_build_query($page_args),
            'extra' => '',
            'searchdata' => $args,
            'container' => '#iframe'
        ));
    }
    // 发货处理
    public function orders_edit()
    {
        $basepath = '/exchange/orders';
        $proid = $this->existsKeyInArray('id', $_GET,'N');
        $item = $this->mod_orders_item($proid);
        if(!$item) core::error('参数错误');
        $html = '<div id="mainbody">';
        $html .= '<div class="main">';
        $html .= '<div class="info">';
        $html .= '<form name="add_save" action="'.$basepath.'_edit_save"  method="POST" target="ajax" func="form_submit">';
        $html .= '<input type="hidden" name="id" class="int" value="'.$proid.'" />';
        $html .= '<dl><dt>快递公司：</dt><dd><input type="text" name="expressltd" class="int" value="'.$item['expressltd'].'" /></dd></dl>';
        $html .= '<dl><dt>快递单号：</dt><dd><input type="text" name="expressnumber" class="int" value="'.$item['expressnumber'].'" /></dd></dl>';
        $html .= '<dl><dt>订单状态：</dt><dd>'.($item['state']==0 ? '待处理' : '已处理').'</dd></dl>';
        $html .= '</form>';
        $html .= '</div>';
        $html .= '</div>';
        $html .= '</div>';
        $this->dialogue(array(
            'class' => '',
            'body' => $html,
            'yes'  => array(
                'text' => '保存',
                'func' => '$("form[name=add_save]").submit();',
            ),
            'no'  => array(
                'text' => '关闭',
            ),
        ));
    }
    // 保存编辑订单
    public function orders_edit_save()
    {
        $args = array(
            'id' => $this->existsKeyInArray('id',$_POST,'N'),
            'expressltd' => $this->existsKeyInArray('expressltd',$_POST,'S'),
            'expressnumber' => $this->existsKeyInArray('expressnumber',$_POST,'S'),
            'state'=>1,
        );
        if(empty($args['expressltd'])) core::error('快递公司不能为空');
        $_result = $this->db->update('@@exchange_orders',$args,array('id'=>$args['id']));
        if(!$_result) core::error("操作失败");
        $this->addLog($this->authid,__FUNCTION__,$_result);
        $this->dialogue(array(
            'type' => 'success',
            'text' => "操作成功",
            'auto' => true,
            'yes'  => array(
                'text' => '刷新',
                'func' => '$("#btn_refresh").trigger("click");',
            ),
            'no'  => array(
                'text' => '返回',
            ),
        ));
    }
    // 退回积分或红豆
    public function orders_backcoin()
    {
        $args = array(
            'id' => $this->existsKeyInArray('id',$_GET,'N'),
            'state' => $this->existsKeyInArray('state',$_GET,'N'),
            'coin' => $this->existsKeyInArray('coin',$_GET,'F'),
        );
        if(empty($args['coin'])) core::error('参数不正确');
        $_result = $this->db->update('@@exchange_orders',$args,array('id'=>$args['id']));
        if(!$_result) core::error("操作失败");
        $this->addLog($this->authid,__FUNCTION__,$_result,$args['id']);
        $this->dialogue(array(
            'type' => 'success',
            'text' => "操作成功",
            'auto' => true,
            'yes'  => array(
                'text' => '刷新',
                'func' => '$("#btn_refresh").trigger("click");',
            ),
            'no'  => array(
                'text' => '返回',
            ),
        ));
    }
    # endregion
}